package cn.wu.reggie.service.impl;

import cn.wu.reggie.common.R;
import cn.wu.reggie.entity.ShoppingCart;
import cn.wu.reggie.mapper.ShoppingCartMapper;
import cn.wu.reggie.service.ShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class ShoppingCartServiceImpl implements ShoppingCartService {


    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Override
    public R add2Cart(ShoppingCart paramCart) {
        //1 通过菜品id或者套餐id 联合用户id去数据库查询有无添加过
        ShoppingCart shoppingCart = shoppingCartMapper.findByDishIdOrSetmealIdWithUserId(paramCart);
        // 2 若没有添加过 就保存
        if (shoppingCart == null) {
            shoppingCart = paramCart;

            shoppingCart.setNumber(1);
            shoppingCart.setCreateTime(LocalDateTime.now());

            shoppingCartMapper.save(shoppingCart);
        } else {
            // 3 若添加过 就修改数量 完成更新
            shoppingCart.setNumber(shoppingCart.getNumber() + 1);

            shoppingCartMapper.update(shoppingCart);
        }

        // 页面上要展示购物项对应的菜品或者套餐的数据 因此返回购物项
        return R.success(shoppingCart);
    }

    @Override
    public R showCart(Long userId) {
        // 1 调用mapper 通过用户id查询所有购物项
        List<ShoppingCart> carts = shoppingCartMapper.findAllByUserId(userId);
        return R.success(carts);
    }

    @Override
    public R cleanCart(Long userId) {
        shoppingCartMapper.deleteByUserId(userId);
        return R.success(null);
    }
}
